{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "code",
      "source": [
        "import asyncio\n",
        "import json\n",
        "import random\n",
        "from dataclasses import dataclass, asdict\n",
        "from typing import Dict, List, Optional, Any\n",
        "from enum import Enum\n",
        "import google.generativeai as genai"
      ],
      "metadata": {
        "id": "Xj-NsQVUlaqc"
      },
      "execution_count": 7,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "API_KEY = None\n",
        "\n",
        "try:\n",
        "    import google.colab\n",
        "    IN_COLAB = True\n",
        "except ImportError:\n",
        "    IN_COLAB = False"
      ],
      "metadata": {
        "id": "uW2xJ7q9lc1h"
      },
      "execution_count": 8,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "class AgentType(Enum):\n",
        "    ANALYZER = \"analyzer\"\n",
        "    RESEARCHER = \"researcher\"\n",
        "    SYNTHESIZER = \"synthesizer\"\n",
        "    VALIDATOR = \"validator\"\n",
        "\n",
        "@dataclass\n",
        "class Message:\n",
        "    sender: str\n",
        "    receiver: str\n",
        "    content: str\n",
        "    msg_type: str\n",
        "    metadata: Dict = None"
      ],
      "metadata": {
        "id": "7pDoP1phleXS"
      },
      "execution_count": 9,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "class GeminiAgent:\n",
        "    def __init__(self, agent_id: str, agent_type: AgentType, network: 'AgentNetwork'):\n",
        "        self.id = agent_id\n",
        "        self.type = agent_type\n",
        "        self.network = network\n",
        "        self.model = genai.GenerativeModel('gemini-2.0-flash')\n",
        "        self.inbox = asyncio.Queue()\n",
        "        self.context_memory = []\n",
        "\n",
        "        self.system_prompts = {\n",
        "            AgentType.ANALYZER: \"You are a data analyzer. Break down complex problems into components and identify key patterns.\",\n",
        "            AgentType.RESEARCHER: \"You are a researcher. Gather information and provide detailed context on topics.\",\n",
        "            AgentType.SYNTHESIZER: \"You are a synthesizer. Combine information from multiple sources into coherent insights.\",\n",
        "            AgentType.VALIDATOR: \"You are a validator. Check accuracy and consistency of information and conclusions.\"\n",
        "        }\n",
        "\n",
        "    async def process_message(self, message: Message):\n",
        "        \"\"\"Process incoming message and generate response\"\"\"\n",
        "        if not API_KEY:\n",
        "            return \"❌ API key not configured. Please set API_KEY variable.\"\n",
        "\n",
        "        prompt = f\"\"\"\n",
        "        {self.system_prompts[self.type]}\n",
        "\n",
        "        Context from previous interactions: {json.dumps(self.context_memory[-3:], indent=2)}\n",
        "\n",
        "        Message from {message.sender}: {message.content}\n",
        "\n",
        "        Provide a focused response (max 100 words) that adds value to the network discussion.\n",
        "        \"\"\"\n",
        "\n",
        "        try:\n",
        "            response = await asyncio.to_thread(\n",
        "                self.model.generate_content, prompt\n",
        "            )\n",
        "            return response.text.strip()\n",
        "        except Exception as e:\n",
        "            return f\"Error processing: {str(e)}\"\n",
        "\n",
        "    async def send_message(self, receiver_id: str, content: str, msg_type: str = \"task\"):\n",
        "        \"\"\"Send message to another agent\"\"\"\n",
        "        message = Message(self.id, receiver_id, content, msg_type)\n",
        "        await self.network.route_message(message)\n",
        "\n",
        "    async def broadcast(self, content: str, exclude_self: bool = True):\n",
        "        \"\"\"Broadcast message to all agents in network\"\"\"\n",
        "        for agent_id in self.network.agents:\n",
        "            if exclude_self and agent_id == self.id:\n",
        "                continue\n",
        "            await self.send_message(agent_id, content, \"broadcast\")\n",
        "\n",
        "    async def run(self):\n",
        "        \"\"\"Main agent loop\"\"\"\n",
        "        while True:\n",
        "            try:\n",
        "                message = await asyncio.wait_for(self.inbox.get(), timeout=1.0)\n",
        "\n",
        "                response = await self.process_message(message)\n",
        "\n",
        "                self.context_memory.append({\n",
        "                    \"from\": message.sender,\n",
        "                    \"content\": message.content,\n",
        "                    \"my_response\": response\n",
        "                })\n",
        "\n",
        "                if len(self.context_memory) > 10:\n",
        "                    self.context_memory = self.context_memory[-10:]\n",
        "\n",
        "                print(f\"🤖 {self.id} ({self.type.value}): {response}\")\n",
        "\n",
        "                if random.random() < 0.3:\n",
        "                    other_agents = [aid for aid in self.network.agents.keys() if aid != self.id]\n",
        "                    if other_agents:\n",
        "                        target = random.choice(other_agents)\n",
        "                        await self.send_message(target, f\"Building on that: {response[:50]}...\")\n",
        "\n",
        "            except asyncio.TimeoutError:\n",
        "                continue\n",
        "            except Exception as e:\n",
        "                print(f\"❌ Error in {self.id}: {e}\")"
      ],
      "metadata": {
        "id": "PO499D7JlhFS"
      },
      "execution_count": 10,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "class AgentNetwork:\n",
        "    def __init__(self):\n",
        "        self.agents: Dict[str, GeminiAgent] = {}\n",
        "        self.message_log = []\n",
        "        self.running = False\n",
        "\n",
        "    def add_agent(self, agent_type: AgentType, agent_id: Optional[str] = None):\n",
        "        \"\"\"Add new agent to network\"\"\"\n",
        "        if not agent_id:\n",
        "            agent_id = f\"{agent_type.value}_{len(self.agents)+1}\"\n",
        "\n",
        "        agent = GeminiAgent(agent_id, agent_type, self)\n",
        "        self.agents[agent_id] = agent\n",
        "        print(f\"✅ Added {agent_id} to network\")\n",
        "        return agent_id\n",
        "\n",
        "    async def route_message(self, message: Message):\n",
        "        \"\"\"Route message to target agent\"\"\"\n",
        "        self.message_log.append(asdict(message))\n",
        "\n",
        "        if message.receiver in self.agents:\n",
        "            await self.agents[message.receiver].inbox.put(message)\n",
        "        else:\n",
        "            print(f\"⚠️  Agent {message.receiver} not found\")\n",
        "\n",
        "    async def initiate_task(self, task: str):\n",
        "        \"\"\"Start a collaborative task\"\"\"\n",
        "        print(f\"🚀 Starting task: {task}\")\n",
        "\n",
        "        analyzer_agents = [aid for aid, agent in self.agents.items()\n",
        "                          if agent.type == AgentType.ANALYZER]\n",
        "\n",
        "        if analyzer_agents:\n",
        "            initial_message = Message(\"system\", analyzer_agents[0], task, \"task\")\n",
        "            await self.route_message(initial_message)\n",
        "\n",
        "    async def run_network(self, duration: int = 30):\n",
        "        \"\"\"Run the agent network for specified duration\"\"\"\n",
        "        self.running = True\n",
        "        print(f\"🌐 Starting agent network for {duration} seconds...\")\n",
        "\n",
        "        agent_tasks = [agent.run() for agent in self.agents.values()]\n",
        "\n",
        "        try:\n",
        "            await asyncio.wait_for(asyncio.gather(*agent_tasks), timeout=duration)\n",
        "        except asyncio.TimeoutError:\n",
        "            print(\"⏰ Network session completed\")\n",
        "        finally:\n",
        "            self.running = False"
      ],
      "metadata": {
        "id": "XZlcCMbYl-GC"
      },
      "execution_count": 11,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "async def demo_agent_network():\n",
        "    \"\"\"Demonstrate the Gemini Agent Network Protocol\"\"\"\n",
        "\n",
        "    network = AgentNetwork()\n",
        "\n",
        "    network.add_agent(AgentType.ANALYZER, \"deep_analyzer\")\n",
        "    network.add_agent(AgentType.RESEARCHER, \"info_gatherer\")\n",
        "    network.add_agent(AgentType.SYNTHESIZER, \"insight_maker\")\n",
        "    network.add_agent(AgentType.VALIDATOR, \"fact_checker\")\n",
        "\n",
        "    task = \"Analyze the potential impact of quantum computing on cybersecurity\"\n",
        "\n",
        "    network_task = asyncio.create_task(network.run_network(20))\n",
        "    await asyncio.sleep(1)\n",
        "    await network.initiate_task(task)\n",
        "    await network_task\n",
        "\n",
        "    print(f\"\\n📊 Network completed with {len(network.message_log)} messages exchanged\")\n",
        "    agent_participation = {aid: sum(1 for msg in network.message_log if msg['sender'] == aid)\n",
        "                          for aid in network.agents}\n",
        "    print(\"Agent participation:\", agent_participation)\n",
        "\n",
        "def setup_api_key():\n",
        "    \"\"\"Interactive API key setup\"\"\"\n",
        "    global API_KEY\n",
        "\n",
        "    if IN_COLAB:\n",
        "        from google.colab import userdata\n",
        "        try:\n",
        "            API_KEY = userdata.get('GEMINI_API_KEY')\n",
        "            genai.configure(api_key=API_KEY)\n",
        "            print(\"✅ API key loaded from Colab secrets\")\n",
        "            return True\n",
        "        except:\n",
        "            print(\"💡 To use Colab secrets: Add 'GEMINI_API_KEY' in the secrets panel\")\n",
        "\n",
        "    print(\"🔑 Please enter your Gemini API key:\")\n",
        "    print(\"   Get it from: https://makersuite.google.com/app/apikey\")\n",
        "\n",
        "    try:\n",
        "        if IN_COLAB:\n",
        "            from google.colab import userdata\n",
        "            API_KEY = input(\"Paste your API key here: \").strip()\n",
        "        else:\n",
        "            import getpass\n",
        "            API_KEY = getpass.getpass(\"Paste your API key here: \").strip()\n",
        "\n",
        "        if API_KEY and len(API_KEY) > 10:\n",
        "            genai.configure(api_key=API_KEY)\n",
        "            print(\"✅ API key configured successfully!\")\n",
        "            return True\n",
        "        else:\n",
        "            print(\"❌ Invalid API key\")\n",
        "            return False\n",
        "    except KeyboardInterrupt:\n",
        "        print(\"\\n❌ Setup cancelled\")\n",
        "        return False"
      ],
      "metadata": {
        "id": "XXrYtLPimAgR"
      },
      "execution_count": 12,
      "outputs": []
    },
    {
      "cell_type": "code",
      "execution_count": 6,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 506
        },
        "id": "1l9anCe6jA9z",
        "outputId": "6a24b103-3413-4560-ac5b-c27688cbd74f"
      },
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "🧠 Gemini Agent Network Protocol\n",
            "========================================\n",
            "💡 To use Colab secrets: Add 'GEMINI_API_KEY' in the secrets panel\n",
            "🔑 Please enter your Gemini API key:\n",
            "   Get it from: https://makersuite.google.com/app/apikey\n",
            "Paste your API key here: ENTER YOUR KEY\n",
            "✅ API key configured successfully!\n",
            "\n",
            "🚀 Starting demo...\n",
            "✅ Added deep_analyzer to network\n",
            "✅ Added info_gatherer to network\n",
            "✅ Added insight_maker to network\n",
            "✅ Added fact_checker to network\n",
            "🌐 Starting agent network for 20 seconds...\n",
            "🚀 Starting task: Analyze the potential impact of quantum computing on cybersecurity\n",
            "🤖 deep_analyzer (analyzer): Quantum computing poses a dual threat and opportunity for cybersecurity.\n",
            "\n",
            "**Threat:** Existing encryption methods (RSA, ECC) become vulnerable to Shor's algorithm, potentially exposing sensitive data.\n",
            "\n",
            "**Opportunity:** Quantum Key Distribution (QKD) and post-quantum cryptography (PQC) offer potentially unbreakable encryption, securing future communications.\n",
            "\n",
            "Impact necessitates a proactive shift: investing in PQC research, developing hybrid classical/quantum security strategies, and preparing for potential data breaches as quantum computers mature.\n",
            "🤖 insight_maker (synthesizer): Okay, understanding the dual threat and opportunity of quantum computing is crucial. While it threatens current encryption, pushing us towards quantum-resistant cryptography, it also offers unprecedented computational power. This power can revolutionize fields like drug discovery, materials science, and AI. The key lies in proactively developing quantum-safe algorithms and simultaneously exploring the beneficial applications of quantum computing itself to maintain a competitive advantage. Investing in both defensive and offensive quantum strategies is essential.\n",
            "⏰ Network session completed\n",
            "\n",
            "📊 Network completed with 2 messages exchanged\n",
            "Agent participation: {'deep_analyzer': 1, 'info_gatherer': 0, 'insight_maker': 0, 'fact_checker': 0}\n"
          ]
        }
      ],
      "source": [
        "if __name__ == \"__main__\":\n",
        "    print(\"🧠 Gemini Agent Network Protocol\")\n",
        "    print(\"=\" * 40)\n",
        "\n",
        "    if not setup_api_key():\n",
        "        print(\"❌ Cannot run without valid API key\")\n",
        "        exit()\n",
        "\n",
        "    print(\"\\n🚀 Starting demo...\")\n",
        "\n",
        "    if IN_COLAB:\n",
        "        import nest_asyncio\n",
        "        nest_asyncio.apply()\n",
        "        loop = asyncio.get_event_loop()\n",
        "        loop.run_until_complete(demo_agent_network())\n",
        "    else:\n",
        "        asyncio.run(demo_agent_network())"
      ]
    }
  ]
}
